package com.LA_houseLease.app.service.impl;

import com.LA_houseLease.app.service.LoginService;
import com.LA_houseLease.app.service.SmsService;
import com.LA_houseLease.app.service.UserInfoService;
import com.LA_houseLease.app.vo.user.LoginVo;
import com.LA_houseLease.app.vo.user.UserInfoVo;
import com.LA_houseLease.common.constant.RedisConstant;
import com.LA_houseLease.common.exception.houseLeaseException;
import com.LA_houseLease.common.properties.JwtProperties;
import com.LA_houseLease.common.result.ResultCodeEnum;
import com.LA_houseLease.common.utils.CodeUtil;
import com.LA_houseLease.common.utils.JwtUtil;
import com.LA_houseLease.pojo.entity.UserInfo;
import com.LA_houseLease.pojo.enums.BaseStatus;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService service;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 获取短信验证码
     * @param phone
     */
    @Override
    public void getCode(String phone) {
        //检查手机号码是否为空
        if (!StringUtils.hasText(phone)) {
            throw new houseLeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        String code= CodeUtil.getRandomCode(6); //获取验证码
        String key= RedisConstant.APP_LOGIN_PREFIX+phone; //设置redis中key
        //限制短信发送
        Boolean hasKey = stringRedisTemplate.hasKey(key); //检查redis中是否已经存在该手机号码的key
        if(hasKey){
            Long ttl = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);//获取TTL
            if(RedisConstant.APP_LOGIN_CODE_TTL_SEC-ttl<RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                //距上次发送短信间隔小于一分钟
                throw new houseLeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        service.sendSMS(phone,code); //发送短信
        stringRedisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS); //存入redis并设置过期时间以及时间单位
    }


    /**
     * 登录
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {
        //1.判断手机号和验证码是否为空
        if(loginVo.getPhone()==null){
            throw new houseLeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if(loginVo.getCode()==null){
            throw new houseLeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //2.校验验证码
        String key=RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone();
        String code = stringRedisTemplate.opsForValue().get(key);
        if(code==null){
            throw new houseLeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if(!code.equals(loginVo.getCode())){
            throw new houseLeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //3.判断用户是否存在
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(lambdaQueryWrapper);
        if(userInfo==null){
            userInfo=new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-"+loginVo.getPhone().substring(6));
            userInfoService.save(userInfo);
        }
        //4.判断用户是否被禁
        if(userInfo.getStatus().equals(BaseStatus.DISABLE)){
            throw new houseLeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //5.创建并返回token
        return JwtUtil.creatToken(jwtProperties.getSecretKey(),jwtProperties.getTtl(),userInfo.getId(),userInfo.getPhone());
    }

    /**
     * 获取登录用户信息
     * @param userId
     * @return
     */
    @Override
    public UserInfoVo getUserInfoVoById(Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        return new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
    }
}


















